package com.yisu.expressway.driver_revelation.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.bm.library.Info;
import com.bm.library.PhotoView;
import com.google.gson.reflect.TypeToken;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.yisu.expressway.R;
import com.yisu.expressway.activity.BaseActivity;
import com.yisu.expressway.databinding.ActivityCreateLiveBinding;
import com.yisu.expressway.network.ApiClientHelper;
import com.yisu.expressway.network.ApiResult;
import com.yisu.expressway.network.ApiSetting;
import com.yisu.expressway.onedollar.widget.DownUpPopupWindow;
import com.yisu.expressway.utils.BitmapUtil;
import com.yisu.expressway.utils.QiniuUploadManager;
import com.yisu.expressway.utils.StringUtil;
import com.yisu.expressway.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CreateLiveActivity extends BaseActivity  implements AndroidImagePicker.OnImagePickCompleteListener,TextWatcher {

    private final static String TAG = CreateLiveActivity.class.getSimpleName();

    ActivityCreateLiveBinding binding;
    private DownUpPopupWindow mDownUpPopupWindow;

    private static final int PHOTO_REQUEST_CAMERA = 200;// 拍照
    private String selectImgPath;
    private Info mInfo;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_create_live);
        initView();
    }

    private void initView(){
        binding.edtTitle.addTextChangedListener(this);
        binding.ivFullImg.enable();
    }

    public void onPickImg(View itemView){
        if(StringUtil.isNullOrEmpty(selectImgPath)) {

            if (mDownUpPopupWindow == null) {
                View view = getLayoutInflater().inflate(R.layout.popwindow_down_up_pic_select, null);
                mDownUpPopupWindow = new DownUpPopupWindow(this, view);
                view.findViewById(R.id.tv_photograph).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickPicFromCamera();
                        dismissPopDlg();
                    }
                });
                view.findViewById(R.id.tv_album).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pickPicFromAlbum();
                        dismissPopDlg();
                    }
                });
                view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dismissPopDlg();
                    }
                });
            }
            mDownUpPopupWindow.showAtLocation(binding.tvCancel, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                    0);

        }else {
            startScale2FullScreen();
        }
    }

    public void onScale2Origin(View view){
        binding.ivFullImg.setBackgroundColor(Color.TRANSPARENT);
        binding.ivFullImg.animaTo(mInfo, new Runnable() {
            @Override
            public void run() {
                binding.ivFullImg.setVisibility(View.GONE);
                binding.ivPickImg.setVisibility(View.VISIBLE);
            }
        });
    }

    private void startScale2FullScreen(){
        mInfo = PhotoView.getImageViewInfo(binding.ivPickImg);
        binding.ivFullImg.setImageDrawable(binding.ivPickImg.getDrawable());
        binding.ivFullImg.setBackgroundColor(Color.BLACK);
        binding.ivPickImg.setVisibility(View.GONE);
        binding.ivFullImg.setVisibility(View.VISIBLE);
        binding.ivFullImg.animaFrom(mInfo);
    }


    public void onPublishLive(View view){
        String title = binding.edtTitle.getText().toString();
        if(StringUtil.isNullOrEmpty(title)){
            ToastUtil.displayShortToastMsg(this,R.string.title_should_not_empty);
            return;
        }

        if(StringUtil.isNowMaxLength(binding.edtTitle.getText().toString(),15)){
            ToastUtil.displayShortToastMsg(this,R.string.text_over_length_notify);
            return;
        }

        if(StringUtil.isNullOrEmpty(selectImgPath)){
            ToastUtil.displayShortToastMsg(R.string.img_is_required);
            return;
        }

        uploadImg2Qiniu();

    }

    public void onFinishPage(View view){
        finish();
    }

    public void dismissPopDlg() {
        if (mDownUpPopupWindow != null && mDownUpPopupWindow.isShowing()) {
            mDownUpPopupWindow.dismiss();
            mDownUpPopupWindow = null;
        }
    }

    private void pickPicFromAlbum() {
        AndroidImagePicker.getInstance().pickSingle(this,false,this);
    }

    private void pickPicFromCamera() {
        try {
            AndroidImagePicker.getInstance().takePicture(this, PHOTO_REQUEST_CAMERA);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setSelectImg(String path){
        selectImgPath = path;
        binding.ivDeletePic.setVisibility(View.VISIBLE);
        Bitmap localImg = BitmapUtil.getLoacalBitmap(path);
        if(localImg != null){
            binding.ivPickImg.setImageBitmap(localImg);
        }
    }

    public void onDeletePic(View view){
        selectImgPath = "";
        binding.ivDeletePic.setVisibility(View.GONE);
        binding.ivPickImg.setImageResource(R.drawable.pic_add);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PHOTO_REQUEST_CAMERA:
                String currentPhotoPath = AndroidImagePicker.getInstance().getCurrentPhotoPath();
                setSelectImg(currentPhotoPath);
                break;
            default:
                break;
        }
    }

    @Override
    public void onImagePickComplete(List<ImageItem> items) {
        if(items != null && items.size() > 0){
            setSelectImg(items.get(0).path);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String inputTitle = s.toString();
        if(!StringUtil.isNullOrEmpty(inputTitle)){
            if(StringUtil.isNowMaxLength(inputTitle,15)){
                ToastUtil.displayShortToastMsg(this,R.string.text_over_length_notify);
            }
        }
    }

    private void uploadImg2Qiniu(){

        binding.tvPost.setEnabled(false);

        String filePath = BitmapUtil.compressBitmap(selectImgPath);//压缩图片
        if (StringUtil.isNullOrEmpty(filePath)) {
            filePath = selectImgPath;
        }

        QiniuUploadManager.getInstance().getTokenAndUploadHeadImg(filePath, new QiniuUploadManager.UpLoadListener() {
            @Override
            public void uploadSuccess(String url, int w, int h) {
                publishNewLive2Server(url);
            }

            @Override
            public void uploadFail(String error) {
                binding.tvPost.setEnabled(true);
                ToastUtil.displayShortToastMsg(CreateLiveActivity.this, TextUtils.isEmpty(error) ? "上传失败" : error);
            }

            @Override
            public void onGetToken(String token) {

            }

            @Override
            public void onGetTokenApiFail(String error) {
                binding.tvPost.setEnabled(true);
                ToastUtil.displayLongToastMsg(CreateLiveActivity.this, error);
            }

            @Override
            public void onGetTokenNetworkFail(VolleyError volleyError) {
                binding.tvPost.setEnabled(true);
                ToastUtil.displayShortToastMsg(CreateLiveActivity.this, "网络不给力");
            }
        });
    }

    private void publishNewLive2Server(String imgPath){
        Map<String, Object> params = new HashMap();
        params.put("image", imgPath);
        params.put("title", binding.edtTitle.getText().toString());

        ApiClientHelper.postApi(ApiSetting.postNewLive(), new TypeToken<Object>() {
        }, new JSONObject(params), new Response.Listener<ApiResult<Object>>() {
            @Override
            public void onResponse(ApiResult<Object> result) {

                binding.tvPost.setEnabled(true);

                if (!result.success) {
                    ToastUtil.displayLongToastMsg(CreateLiveActivity.this, result.getMsg());
                    return;
                }

                ToastUtil.displayShortToastMsg(R.string.publish_live_success);
                EventBus.getDefault().post(RevelationActivity.NEW_LIVE_POST);
                finish();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                binding.tvPost.setEnabled(true);
                ToastUtil.displayShortToastMsg(CreateLiveActivity.this, volleyError.getMessage());
            }
        }, this);
    }
}
